export default {
    namespaced:true,
    state:{
        name:"购物车cart",
        carts:[],
    },
    actions:{
        ADD_TO_CART(context, payload) {

            // console.log(context)
            // console.log(payload)
            context.commit('SET_CART',payload)
            context.commit('product/DECREASE_INVENTORY',payload,{ root:true })
        },
        REMOVE_CART(context,payload) {
            // console.log(payload) 
            context.commit('DECREASE_CART',payload)
            context.commit('product/INCREASE_INVENTORY',payload,{ root:true })
        }
    },
    getters:{
        total(state){
            return (state.carts.reduce((total,item) => {
                return total += item.count * item.price
            },0)).toFixed(2)
        }
    },
    mutations:{
        LOG(state){
            console.log(state)
        },
        SET_CART(state, payload) {

            let target = state.carts.find(item => item.id === payload.id)
            if(target){
                target.count++
            }else {
                let obj = {
                    id: payload.id,
                    title:payload.title,
                    price:payload.price,
                    count:1
                }
                state.carts.push(obj)
            }   
        },
        DECREASE_CART(state,payload){
            // payload.count--
            let target = state.carts.find(item => item.id === payload.id)

            if(target) {
                target.count--
            }

            if(target.count === 0){
                state.carts = state.carts.filter(item => item.id !=target.id)
            }
        },


        // INCREASE_INVENTORY(state,payload){
        //     let target = state.products.find(item => item.id === payload.id)

        //     if(target) {
        //         target.inventory++
        //     }
        // },

        
    },
}